import {
  personInfo,
  addressInfo,
  getDiscount,
  getPackFee,
  getTableWare,
  getDeliveryFee,
  orderAdd,
  defaultAddressInfo
} from "../../../http/api"
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    oldId: "",
    oldInfo: {},
    addressId: "",
    addressInfo: {},
    startDate: "",

    planArr: [
      "每天连续配送",
      "周一至周五(周六周日不配送)",
      "自定义配送方案"
    ],
    planType: 0,
    dateArr: [],
    todayStr: "",

    discount: 0,
    disType: 0,
    disAmount: 0,

    goodsTotal: 0,

    deliveryFee: 0,
    deliveryFeeOnce: 0,
    deliveryFeeTaoCan: 0,

    packFee: 0,
    packFeeOnce: 0,
    packFeeTaocan: 0,


    isNeedDeposit: false,
    hasDeposit: false,
    isDeposit: false,
    deposit: 0, //押金



    deliveryDays: 0,
    monthDays: 0,
    daysArr: [],


    orderTotal: 0,
    currentMonthDays: 0,
    nextMonthDays: 0,
    memo: ""
  },

  handleCancleOld() {
    this.setData({
      oldId: ""
    })
    wx.removeStorageSync('orderOld')

  },


  clearOrderStorage() {
    // wx.clearStorageSync("")
    wx.removeStorageSync('orderDeliveryDays');
    wx.removeStorageSync('orderStartDate');
    wx.removeStorageSync('orderPlanType');
    wx.removeStorageSync('orderAddress');
    wx.removeStorageSync('orderOld');
    wx.removeStorageSync('orderDateArr');

  },
  handlePay() {
    const that = this
    if (!wx.getStorageSync('orderAddress')) {
      wx.showModal({
        title: '提示',
        content: '请选择收获地址',
        showCancel: false,
      })
      return
    }



    const orderDetailList = this.data.goodsArr.map(item => {
      const goodsObj = {}
      goodsObj.goodName = item.name;
      goodsObj.goodPrice = item.price;
      goodsObj.goodAmount = item.num;
      goodsObj.goodPriceOld = item.oldPrice;
      goodsObj.goodPic = item.image;
      return goodsObj
    });

    let orderDates = []
    let orderDatesStr = ""
    let tablewarePrice = 0
    if (this.data.isDeposit) {
      tablewarePrice = this.data.deposit
    }

    if (this.data.planType == 2) {
      const orderDateArr = wx.getStorageSync('orderDateArr')
      if (orderDateArr.length === 0 || !orderDateArr) {
        wx.showModal({
          title: '提示',
          content: '请选择配送日期',
        })

        return
      }
      orderDates = orderDateArr.filter((item) => {
        return item.isSelected
      })

      orderDatesStr = orderDates.reduce((pre, item, index) => {
        if (index === 0) {
          return pre + `${item.dateYear}-${item.dateMonth}-${item.dateDay}`
        } else {
          return pre + `,${item.dateYear}-${item.dateMonth}-${item.dateDay}`
        }

      }, "")
    }

    const params = {
      customerId: wx.getStorageSync('id'),
      personId: wx.getStorageSync('orderOld'),
      addressId: wx.getStorageSync('orderAddress'),
      startDate: wx.getStorageSync('orderStartDate'),
      orderType: 1, //订单类型  0-外卖  1-包月  2-堂食  3-餐具押金
      goodPrice: this.data.goodsTotal,
      deliveryPrice: this.data.deliveryFee,
      packPrice: this.data.packFee,
      subsidyPrice: this.data.discount,
      amountPrice: this.data.orderTotal,
      deliveryPlan: wx.getStorageSync('orderPlanType'), //0-连续30日 ; 1-周1至周五; 2-自定义日期;
      status: 0,
      memo: this.data.memo,
      orderDetailList: orderDetailList,
      orderDates: orderDatesStr,
      days: this.data.deliveryDays,
      tablewarePrice
    }
    wx.showModal({
      title: '提示',
      content: '确认提交该订单吗？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading()
          orderAdd(params).then(res => {
            if (res.data.code == 200) {
              const {id} = res.data.data

              // 消息订阅(商家确认消息)
              app.userSubscribeMessageMonthConfirm()
              
              wx.showModal({
                title: '提示',
                content: '订单已成功提交，请等待商家确认',
                complete: (res) => {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/user/order/order',
                    })
                  }
                }
              })

            



            } else {
              wx.showModal({
                title: '提示',
                content: '订单异常请重新提交',
              })
            }
          }).finally(() => {
            wx.hideLoading()
          })

        }
      }
    })
  },

  toPage(e) {
    const {
      url
    } = e.currentTarget.dataset

    wx.navigateTo({
      url
    })
  },


  //更改配送天数
  handleChangeDays(e) {

    const index = e.detail.value
    this.setData({
      deliveryDays: this.data.daysArr[index]
    })
    wx.setStorageSync('orderDeliveryDays', this.data.daysArr[index])
    wx.removeStorageSync('orderDateArr')

    this.goodsCalculator()
    this.discountCalculator()
    this.deliveryFeeCalculator()
    this.packFeeCalculator()
    this.orderCalculator()

  },

  //更改配送开始时间
  handleChangeDate(e) {
    const startDate = e.detail.value
    this.setData({
      startDate
    })
    wx.setStorageSync('orderStartDate', startDate)
    wx.removeStorageSync('orderDateArr')
  },


  //补贴计算器
  discountCalculator() {


    const {
      disType,
      disAmount,
      goodsTotal,
      deliveryDays,
      currentMonthDays,
      nextMonthDays,
      oldId
    } = this.data

    if (!oldId) {
      return
    }
    let discount = 0

    if (disType == 0) {
      discount = (1 - disAmount) * goodsTotal
    } else {
      discount = disAmount * deliveryDays
    }





    this.setData({
      discount: discount.toFixed(1)
    })
    this.orderCalculator()
  },

  //配送费计算器
  deliveryFeeCalculator() {
    const {
      deliveryFeeOnce,
      deliveryDays,
      goodsArr,
      currentMonthDays,
      nextMonthDays,
      deliveryFeeTaoCan
    } = this.data
    let deliveryFee = 0
    const towMonthDays = currentMonthDays + nextMonthDays;

    if (deliveryDays < currentMonthDays) {
      deliveryFee = deliveryFeeOnce * deliveryDays * goodsArr.length
    } else {
      deliveryFee = deliveryFeeTaoCan * deliveryDays * goodsArr.length
    }

    this.setData({
      deliveryFee: deliveryFee.toFixed(1)
    })
    this.orderCalculator()
  },


  //打包费计算器
  packFeeCalculator() {
    const {
      packFeeOnce,
      deliveryDays,
      goodsArr,
      currentMonthDays,
      nextMonthDays,
      packFeeTaoCan
    } = this.data
    let packFee = 0
    const towMonthDays = currentMonthDays + nextMonthDays;

    const goodsNum = goodsArr.reduce((pre, cur) => {
      return pre + cur.num
    }, 0)

    if (deliveryDays < currentMonthDays) {
      packFee = packFeeOnce * deliveryDays * goodsNum
    } else {
      packFee = packFeeTaoCan * deliveryDays * goodsNum
    }

    this.setData({
      packFee: packFee.toFixed(1)
    })
    this.orderCalculator()

  },


  //商品金额计算器
  goodsCalculator() {
    const {
      currentMonthDays,
      nextMonthDays,
      deliveryDays
    } = this.data
    const towMonthDays = currentMonthDays + nextMonthDays;

    const goodsTotal = this.data.goodsArr.reduce((pre, cur) => {

      if (deliveryDays < currentMonthDays) {
        return pre + cur.oldPrice * cur.num * deliveryDays
      } else {
        return pre + cur.price * cur.num * deliveryDays
      }

    }, 0)

    this.setData({
      goodsTotal: goodsTotal.toFixed(1)
    })
    this.orderCalculator()


  },


  //订单计算器
  orderCalculator() {
    const {
      discount,
      goodsTotal,
      deliveryFee,
      packFee,
      isDeposit,
      deposit
    } = this.data

    let orderTotal = parseFloat(goodsTotal) + parseFloat(deliveryFee) + parseFloat(packFee) - parseFloat(discount);



    if (isDeposit) {
      orderTotal = orderTotal + parseFloat(deposit)
    }
    this.setData({
      orderTotal: orderTotal.toFixed(1)
    })
  },


  //获取下月自然月天数
  getDaysInNextMonth() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 2;

    return new Date(year, month, 0).getDate();
  },


  //获取当前自然月天数
  getDaysInMonth() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    return new Date(year, month, 0).getDate();
  },


  handleChangeDepsit(e) {
    // console.log(e)
    this.setData({
      isDeposit: e.detail
    })

    this.orderCalculator()

  },

  //初始化餐桶押金
  initDeposit() {


    wx.showLoading()
    getTableWare({
      customerId: wx.getStorageSync('id'),
      orderType: 1
    }).then(res => {
      if (res.data.code === 200) {


        this.setData({
          isNeedDeposit: res.data.data.isNeed,
          hasDeposit: res.data.data.isHave,
          deposit: res.data.data.price
        })
      }

    }).finally(() => {
      wx.hideLoading()
    })
  },

  //初始化配送天数
  initDays() {
    const daysArr = []
    const {
      currentMonthDays,
      nextMonthDays
    } = this.data
    const towMonthDays = currentMonthDays + nextMonthDays

    for (let i = 0; i <= towMonthDays; i++) {
      daysArr.push(i)
    }
    this.setData({
      daysArr
    })
    let deliveryDays = wx.getStorageSync('orderDeliveryDays')
    if (deliveryDays) {
      this.setData({
        deliveryDays
      })
    } else {

      deliveryDays = this.getDaysInMonth()
      this.setData({
        deliveryDays
      })

      wx.setStorageSync('orderDeliveryDays', deliveryDays)

    }
    // this.
  },

  //初始化打包费
  async initPackFee() {
    wx.showLoading()
    const onceRes = await getPackFee({
      orderType: 0
    });
    const taocanRes = await getPackFee({
      orderType: 1
    });
    if (onceRes.data.code === 200) {
      this.setData({
        packFeeOnce: onceRes.data.data.price
      })
    }
    if (taocanRes.data.code === 200) {
      this.setData({
        packFeeTaoCan: taocanRes.data.data.price
      })
    }
    wx.hideLoading()

    this.packFeeCalculator()





  },

  //初始化配送费
  async initDeliveryFee() {
    //获取单品配送费
    const resOnce = await getDeliveryFee({
      distance: this.data.addressInfo.distance,
      feeType: 0,
      orderType: 0
    })


    if (resOnce.data.code === 200) {
      this.setData({
        deliveryFeeOnce: resOnce.data.data
      })
    }

    //获取套餐配送费
    const resTaoCan = await getDeliveryFee({
      distance: this.data.addressInfo.distance,
      feeType: 0,
      orderType: 1
    })

    if (resTaoCan.data.code === 200) {
      this.setData({
        deliveryFeeTaoCan: resTaoCan.data.data
      })
    }
    this.deliveryFeeCalculator()

  },

  // 初始化
  async initData() {

    const goodsArr = wx.getStorageSync('cart');
    const oldId = wx.getStorageSync('orderOld');
    const addressId = wx.getStorageSync('orderAddress');
    const startDate = wx.getStorageSync('orderStartDate');
    const planType = wx.getStorageSync('orderPlanType');
    const currentMonthDays = this.getDaysInMonth();
    const nextMonthDays = this.getDaysInNextMonth();
    this.setData({
      currentMonthDays,
      nextMonthDays
    })
    this.setData({
      goodsArr
    })
    this.initDays()
    this.initPackFee()
    // this.initDeposit()//餐桶押金
    this.goodsCalculator()


    //是否有老人缓存
    if (oldId) {
      this.setData({
        oldId
      })
      wx.showLoading()
      const oldRes = await personInfo(oldId)

      if (oldRes.data.code === 200) {
        this.setData({
          oldInfo: {
            ...oldRes.data.data
          }
        })

        const discountRes = await getDiscount({
          idcard: oldRes.data.data.idcard
        })

        if (discountRes.data.code === 200) {
          const {
            disType,
            amount
          } = discountRes.data.data;
          this.setData({
            disType,
            disAmount: amount
          })
        }

        this.discountCalculator()
        this.orderCalculator()

        wx.hideLoading()
      }

    }


    //是否有地址缓存
    if (addressId) {
      this.setData({
        addressId
      })
      this.getAddressInfo(addressId);
    } else {
      this.getDefaultAddressInfo()
    }


    //是否有开始日期缓存
    if (startDate) {
      this.setData({
        startDate
      })
    } else {
      const today = new Date();
      let year = today.getFullYear();
      let month = today.getMonth() + 1;
      let date = today.getDate();
      if (month < 10) {
        month = '0' + month
      }
      if (date < 10) {
        date = '0' + date
      }
      const res = `${year}-${month}-${date}`;
      this.setData({
        startDate: res,
        todayStr: res
      })
      wx.setStorageSync('orderStartDate', res)
    }

    //是否有配送计划缓存
    if (planType) {
      this.setData({
        planType
      })
      wx.setStorageSync('orderPlanType', planType)
    } else {
      this.setData({
        planType: 0
      })
      wx.setStorageSync('orderPlanType', 0)
    }

  },


  //获取默认地址信息
  getDefaultAddressInfo() {
    wx.showLoading()
    defaultAddressInfo({
      customerId: wx.getStorageSync('id')
    }).then(res => {
      if (res.data.code === 200) {
        this.setData({
          addressInfo: {
            ...res.data.data
          }
        })
        this.setData({
          addressId: res.data.data.id
        })
        wx.setStorageSync('orderAddress', res.data.data.id)
        this.initDeliveryFee()


      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  getAddressInfo(addressId) {
    wx.showLoading()
    addressInfo(addressId).then(res => {
      if (res.data.code === 200) {
        this.setData({
          addressInfo: {
            ...res.data.data
          }
        })
        this.initDeliveryFee()
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {


    this.initData()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})